package com.leo.ibatis.demo.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.leo.ibatis.demo.criteria.ProductCriteria;
import com.leo.ibatis.demo.domain.Product;
import com.leo.ibatis.demo.service.ProductService;

public class ProductController extends MultiActionController {

	private ProductService productService;

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ProductCriteria productCriteria = new ProductCriteria();
		bind(request, productCriteria);
		
		List<Product> productList = productService.listOnPage(productCriteria);
		
		ModelAndView mav = new ModelAndView("product/list");
		mav.addObject("productList", productList);
		mav.addObject("productCriteria", productCriteria);
		
		return mav;
	}

	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response) throws Exception {
		ProductCriteria productCriteria = new ProductCriteria();
		bind(request, productCriteria);
			
		String productid = ServletRequestUtils.getRequiredStringParameter(request, "productid");

		Product product = productService.select(productid);
		
		ModelAndView mav = new ModelAndView("product/detail");
		mav.addObject("product", product);
		mav.addObject("productCriteria", productCriteria);
		
		return mav;
	}

	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String productid = ServletRequestUtils.getRequiredStringParameter(request, "productid");

		productService.delete(productid);
		
		return new ModelAndView("redirect:product.do");
	}

}
